/* eslint-disable camelcase */
import axios from 'axios'
import { Dialog } from 'vant'
import VueCookies from 'vue-cookies'
import store from '@/store'

axios.defaults.retry = 3
axios.defaults.timeout = 10000

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_SHOP_API,
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    // config.headers["Content-Type"] = "Content-Type':'multipart/form-data"
    var userId = VueCookies.get('userId')
    var expiresIn = VueCookies.get('expires_in')
    var token = VueCookies.get('token')
    userId = userId ? userId : store.state.app.userId
    expiresIn = expiresIn ? expiresIn : store.state.app.expires_in
    if (userId && token && expiresIn) {
      if (!config.params) {
        config.params = {}
      }
      config.params.token = token
      config.params.expires_in = expiresIn
      config.params.userId = userId
      // config.params = {
      //   "token": accss_token,
      //   "phone": mobile,
      //   ...config.params
      // }
      // config.headers['Authorization'] = token + "-" + phone// 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // console.log(config)
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)
//
// // respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // alert(res.errno)
    // alert(JSON.stringify(response.data))
    if (res && res.errno && res.errno !== 0) {
      // -100 Token 过期了;
      if (res.errno === 401) {
        // localStorage.clear()
        let url = process.env.VUE_APP_BDCHATS_API + '/weixin/auth/login?webCallBack=' + window.location.href
        if(url.indexOf("?") != -1){
            url = url.split("?")[0];
        }
        // window.location.href = url
        return Promise.reject()
      } else {
        Dialog.alert({
          title: '',
          message: res.errmsg
        }).then(() => {
          // on close
        })
        return response.data
      }
    } else {
      return response.data
    }
  },
  error => {
    var config = error.config
    if (!config || !config.retry) {
      Dialog.alert({
        title: '',
        message: error.message
      }).then(() => {
        // on close
      })
      return Promise.reject(error)
    }
    config.__retryCount = config.__retryCount || 0;

    if (config.__retryCount >= config.retry) {
      Dialog.alert({
        title: '',
        message: error.message
      }).then(() => {
        // on close
      })
      return Promise.reject(error)
    }
    config.__retryCount += 1
    var backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve()
      }, config.retryDelay || 1)
    })

    return backoff.then(function () {
      return axios(config)
    })
  }
)

export default service
